let hideIds = [];
let displayIds = [];

/**
 * 设置排序
 */
function setSort() {
    $.messager.prompt("设置菜单排序", "请输入排序号", function(pxh) {
        if (pxh) {
            let data = $("#menu_tree").tree("getSelected");

            if (data) {
                ajaxPost("/user_menu/setSort", {
                    menuId: data.id,
                    pxh: pxh
                }, function (resp) {
                    $.messager.show({
                        title: "系统消息",
                        type: "slide",
                        msg: resp.message
                    });

                    $("#menu_tree").tree("reload");
                }, error);
            }
        }
    });
}

/**
 * 折叠全部
 * @param selector 选择器
 */
function collapseAll(selector) {
    $(selector).tree("collapseAll");
}

/**
 * 展开全部
 * @param selector 选择器
 */
function expandAll(selector) {
    $(selector).tree("expandAll");
}

/**
 * 勾选树节点
 * @param checked 勾选状态
 * @param menuId 树的ID，也就是菜单ID
 */
function checkNode(checked, menuId) {
    if (checked) {
        if (displayIds.length === 0 || displayIds.indexOf(menuId) === -1) {
            displayIds.push(menuId);
        }

        if (hideIds.length > 0) {
            for (let i = 0; i < hideIds.length; i++) {
                if (hideIds[i] === menuId) {
                    hideIds.splice(i, 1);
                }
            }
        }
    } else {
        if (hideIds.length === 0 || hideIds.indexOf(menuId) === -1) {
            hideIds.push(menuId);
        }

        if (displayIds.length > 0) {
            for (let i = 0; i < displayIds.length; i++) {
                if (displayIds[i] === menuId) {
                    displayIds.splice(i, 1);
                }
            }
        }
    }
}

/**
 * 保存菜单树的修改
 */
function saveChange() {
    // 任意数组不为空时才发送ajax请求
    if (displayIds.length > 0 || hideIds.length > 0) {
        ajaxPost("/user_menu/control", {
            displayIds: JSON.stringify(displayIds),
            hideIds: JSON.stringify(hideIds)
        }, function (resp) {
            hideIds = [];
            displayIds = [];

            $.messager.show({
                title: "系统消息",
                type: "slide",
                msg: resp.message
            });

            $("#menu_tree").tree("reload");
            // 删除菜单缓存
            localStorage.removeItem("pms:left_menus");
        }, error);
    }

    $("#tree_dialog").dialog("close");
}

function createFrame(url) {
    return "<iframe src='" + url + "' width='100%' height='98%' frameBorder='0'></iframe>";
}

/**
 * 初始化左侧菜单
 */
function initLeftMenu() {
    // 获取缓存数据
    let leftMenus = localStorage.getItem("pms:left_menus");

    // 缓存不为空，不用请求后端
    if (leftMenus) {
        render(JSON.parse(leftMenus));
    } else {
        ajaxGet("/user_menu/selectLeftMenu", {}, function (resp) {
            let data = resp.data;

            render(data);

            // 缓存到localStorage
            localStorage.setItem("pms:left_menus", JSON.stringify(data));
        });
    }

    function render(data) {
        $("#tabs").tabs({
            border: false,
            onSelect: function(title) {
                localStorage.setItem("pms:currentTab", title);

                console.log("切换当前标签页：" + title);

                let currTab = $("#tabs").tabs("getTab", title);
                let iframe = $(currTab.panel("options").content);
                let src = iframe.attr("src");

                if (src) {
                    $("#tabs").tabs("update", {
                        tab: currTab,
                        options: {
                            content: createFrame(src)
                        }
                    });
                }
            },
            onClose: function (title, index) {
                let pms_tabs = localStorage.getItem("pms:tabs");
                let tabs = JSON.parse(pms_tabs);

                // 删除关闭的tabs
                tabs = tabs.filter(function (item) {
                    return item.title !== title;
                });

                localStorage.setItem("pms:tabs", JSON.stringify(tabs));
            }
        });

        for (let i = 0; i < data.length; i++) {
            let menu = data[i];
            let menus = "";

            // 如果是父菜单
            if (menu.children && menu.children.length > 0) {
                let children = menu.children;

                for (let i = 0; i < children.length; i++) {
                    menus += "<div class='left_nav'>";
                    menus += "<a href='javascript:void(0)' ref='" + children[i].url + "'>" + children[i].name + "</a>";
                    menus += "</div>";
                }
            }

            $("#left_menus").accordion("add", {
                title: menu.name,
                content: menus,
                iconCls: menu.iconClass
            });
        }

        $("#left_menus div > a").on("click", function () {
            let title = $(this).html();
            let url = $(this).attr("ref");

            addTab(title, url);
        });
    }
}

/**
 * 添加tabs标签页
 */
function addTab(title, url) {
    // 选项卡不存在时才添加
    let exists = $("#tabs").tabs("exists", title);

    if (!exists) {
        $("#tabs").tabs("add", {
            title: title,
            closable: true,
            content: createFrame(url)
        });

        let pms_tabs = localStorage.getItem("pms:tabs");
        let tabs = [];

        if (pms_tabs != null) {
            tabs = JSON.parse(pms_tabs);
        }

        tabs.push({
            "title": title,
            "url": url
        });

        localStorage.setItem("pms:tabs", JSON.stringify(tabs));
    } else {
        $("#tabs").tabs("select", title);
    }

    localStorage.setItem("pms:currentTab", title);

}

$(document).ready(function () {

    /**
     * 接口文档
     */
    $("#doc").linkbutton({
        iconCls: "icon-remove",
        text: "接口文档"
    }).on("click", function () {
        $("#tabs").tabs("add", {
            title: "接口文档",
            closable: true,
            content: createFrame("/doc.html")
        });
    });

    /**
     * 退出登录
     */
    $("#logout").linkbutton({
        iconCls: "icon-cancel",
        text: "退出登录"
    }).on("click", function () {
        $.messager.confirm("确认提示", "确认退出登录？", function (result) {
            if (result) {
                ajaxPost("/user/logout", {}, function () {
                    location.href = "/login.html";
                }, error);
            }
        });
    });

    /**
     * 菜单控制
     */
    $("#menu-control").linkbutton({
        iconCls: "icon-ok",
        text: "菜单控制"
    }).on("click", function () {
        $("#menu_tree").tree("reload");

        $("#tree_dialog").dialog("open");
    });

    $("#menu_tree").tree({
        url: "/user_menu/selectMenuTree",
        method: "get",
        lines: true,
        animate: true,
        checkbox: true,
        onlyLeafCheck: false,
        formatter: function(node) {
            if (node.children || node.pxh == null) {
                return node.text;
            } else {
                // 子菜单才显示排序号
                return node.text + "[" + node.pxh + "]";
            }
        },
        onContextMenu: function(e, node) {
            e.preventDefault();

            // 菜单树的子节点才显示右键菜单
            if (!node.children) {
                // 选中该树节点
                $("#menu_tree").tree("select", node.target);

                // 显示右键菜单
                $("#menu_tree-right-menu").menu("show", {
                    left: e.pageX,
                    top: e.pageY
                });
            }
        },
        onCheck: function (node, checked) {
            let children = node.children;

            // 父节点点击复选框
            if (children && children.length > 0) {
                for (let i = 0; i < children.length; i++) {
                    checkNode(checked, children[i].id);
                }
            } else {
                checkNode(checked, node.id);
            }
        }
    });

    $("#tree_dialog").dialog({
        title: "菜单控制",
        modal: true,
        closed: true,
        closable: true,
        draggable: false,
        buttons: [{
            iconCls: "icon-ok",
            text: "确定",
            handler: function() {
                saveChange();
            }
        }]
    });

    initLeftMenu();

    /**
     * 恢复已打开的tab
     */
    // 获取打开的标签页
    let pms_tabs = localStorage.getItem("pms:tabs");

    if (pms_tabs) {
        let tabs = JSON.parse(pms_tabs);

        if (tabs && tabs.length > 0) {
            // 得到当前tab
            let currentTab = localStorage.getItem("pms:currentTab");

            for (let i = 0; i < tabs.length; i++) {
                let tab = tabs[i];

                addTab(tab.title, tab.url);
            }

            // 选中当前tab
            if (currentTab) {
                $("#tabs").tabs("select", currentTab);

                console.log("恢复当前标签页：" + currentTab);
            }
        }
    }

});